package com.gdgk.shop.api.listener;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gdgk.shop.bean.event.PaySuccessOrderEvent;
import com.gdgk.shop.bean.model.Order;
import com.gdgk.shop.bean.model.OrderSettlement;
import com.gdgk.shop.dao.OrderMapper;
import com.gdgk.shop.dao.OrderSettlementMapper;
import com.gdgk.shop.service.OrderSettlementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("defaultPaySuccessListener")
public class PaySuccessOrderListener {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderSettlementMapper orderSettlementMapper;


    @Autowired
    private OrderSettlementService orderSettlementService;

    @EventListener(PaySuccessOrderEvent.class)
    public void defaultPaySuccessOrderEvent(PaySuccessOrderEvent event) {
        List<Order> orders = event.getOrders();
        String bizPayNo = event.getBizPayNo();
        String payNo = event.getPayNo();
        Order order = orders.get(0);
        OrderSettlement orderSettlement = orderSettlementMapper.selectOne(new LambdaQueryWrapper<OrderSettlement>().eq(OrderSettlement::getPayNo, payNo));
        if (StrUtil.isEmpty(bizPayNo)) {
            //更新订单表tz_order的支付信息
            order.setPayTime(new Date());
            order.setStatus(2);
            order.setIsPayed(1);
            orderMapper.updateById(order);
            //更新结算表tz_order_settlement的信息
            orderSettlement.setPayAmount(0.00);
            orderSettlement.setIsClearing(1);
            orderSettlement.setPayStatus(1);
            orderSettlementMapper.updateById(orderSettlement);
        } else {
            //更新订单表tz_order的支付信息
            order.setPayTime(new Date());
            order.setStatus(2);
            order.setIsPayed(1);
            orderMapper.updateById(order);
            orderSettlementService.updateSettlementsByPayNo(payNo, bizPayNo);
        }
    }
}
